package com.coovane.bytetrix.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *     Spring框架应用上下文工具类
 * </p>
 *
 * @author: Hsu
 * @date: 2023/3/30 21:34
 * @copyright: companyName
 * @see
 * @since 1.8
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public ApplicationContextUtils() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    private static void assertApplicationContext() {
        if (applicationContext == null) {
            throw new RuntimeException("ApplicationContext属性为null,请检查是否注入了ApplicationContextUtils!");
        }
    }

    public static <T> T getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }

    public static <T> List<T> getBeanOfType(Class<T> requiredType) {
        assertApplicationContext();
        Map<String, T> map = applicationContext.getBeansOfType(requiredType);
        return map == null ? null : new ArrayList(map.values());
    }

}
